package com.mongdb.demo.service;

import com.mongdb.demo.model.SysUser;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

@Service
public class SysUserServiceImpl implements SysUserService{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void saveUser(SysUser user) {
        mongoTemplate.save(user);
    }

    @Override
    public SysUser findUserByUserName(String userName) {
        Query query=new Query(Criteria.where("userName").is(userName));
        SysUser user =  mongoTemplate.findOne(query , SysUser.class);
        return user;
    }

    @Override
    public int updateUser(SysUser user) {
        Query query=new Query(Criteria.where("user_id").is(user.getUser_id()));
        Update update= new Update().set("userName", user.getUser_name()).set("passWord", user.getPassword());
        //更新查询返回结果集的第一条
        UpdateResult result =mongoTemplate.updateFirst(query,update,SysUser.class);
        //更新查询返回结果集的所有
        // mongoTemplate.updateMulti(query,update,UserEntity.class);
        if(result!=null)
            return (int) result.getMatchedCount();//return long;
        else
            return 0;
    }

    @Override
    public void deleteUserById(String user_id) {
        Query query=new Query(Criteria.where("user_id").is(user_id));
        mongoTemplate.remove(query,SysUser.class);
    }
}
